#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This API is designed to be a special use tool for retaining
and returning site configuration and initialization information.
"""

from string import Template
from tack.db import query, sql_string, sql_int, sql_date
from tack.lib import string_app, json_app, content_headers, status_codes
from tack.lib.configfile import ConfigFile
from tack.lib.modtools import load_config
from tack.lib.dicttools import query_to_list
from util import build_row_dict_for_sql, fill_dict_from_form, build_columns_values_sql, state_def


class Sql:
    get_tmpo_email_data = """
    SELECT subject,
           markup,
           keyword
    FROM message_template
    WHERE keyword like '%$keyword%'
    """
    
    update_tmpo_email_data = """
    UPDATE message_template
    set
    subject = $subject,
    markup = $markup
    WHERE keyword = $keyword
    """
    

def get_public(environ, start_response):
    cfg = environ['tack.siteconfig']
    output = {
        'tmpo_poc_name':cfg['tmpo_poc_name'],
        'tmpo_poc_email':cfg['tmpo_poc_email'],
        'tmpo_poc_phone':cfg['tmpo_poc_phone']
        }
    return json_app(output)(environ, start_response)
    
def post_public(environ, start_response):
    cfg = load_config(environ)
    form = environ['form']
    fields = ['tmpo_poc_name', 'tmpo_poc_email', 'tmpo_poc_phone']
    for k in fields:
        if k in form:
            cfg.set(k,form[k])
    cfg.save(cfg.filename)
    return json_app('Updated')(environ, start_response)

def get_email_data(environ, start_response):
    keyword = 'tmpo'
    sql = Sql.get_tmpo_email_data
    sql = Template(sql).substitute(locals())
    cursor = environ['connection'].cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    output = {}
    labels = ['subject','markup', 'keyword'] 
    output['emails'] = query_to_list(rows, labels)
    return json_app(output)(environ, start_response)
    
def update_email_data(environ, start_response):
    form = environ['form']
    keyword = sql_string(form['keyword'])
    markup = sql_string(form['markup'])
    subject = sql_string(form['subject'])
    sql = Sql.update_tmpo_email_data
    sql = Template(sql).safe_substitute(locals())
    cursor = environ['connection'].cursor()    
    cursor.execute(sql)
    environ['connection'].commit()
    output = 'Email Message Updated'
    return string_app(output)(environ, start_response)    
    
    